package com.xiaouyudeguang.common.discript.service.impl;

import com.xiaouyudeguang.common.annotation.ApiService;
import com.xiaouyudeguang.common.cache.RedisCache;
import com.xiaouyudeguang.common.discript.dao.DiScriptDao;
import com.xiaouyudeguang.common.discript.entity.DiScript;
import com.xiaouyudeguang.common.discript.service.DiScriptService;
import com.xiaouyudeguang.common.service.impl.AbstractServiceImpl;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@ApiService(dataScope = false)
public class DiScriptServiceImpl extends AbstractServiceImpl<DiScriptDao, DiScript> implements DiScriptService {

    private static final String key = "script:%s:%s:%s";

    @Value("${api.cache.enabled:true}")
    private boolean isCache;

    @Override
    public String getScript(String tenantId, String appId, String tableName, String tableApi) throws IOException {
        String cacheKey = String.format(key, tenantId, tableName, tableApi);
        String script = RedisCache.get(cacheKey);
        if (!isCache || isBlank(script)) {
            try {
                DiScript discript = getOne(limitWrapper(tenantId, appId).eq(DiScript::getTableName, tableName).eq(DiScript::getTableApi, tableApi));
                script = discript == null || isBlank(discript.getScript()) ? "" : discript.getScript();
                RedisCache.set(cacheKey, script, 10, TimeUnit.MINUTES);
            } catch (Exception ignored){

            }
        }
        return script;
    }
}